﻿using AutoMapper;
using Basic.Traceability.Domain.Products;
using Basic.Traceability.ErrorCode;
using Basic.Traceability.Host.Api.Read.Application.Command.Products.TraceableProducts;
using Basic.Traceability.Host.Api.Read.Dto;
using Basic.Traceability.Intrestructrue.Base;
using MediatR;

namespace Basic.Traceability.Host.Api.Read.Application.Handler.Products.TraceableProducts
{
    public class GetTraceableProductsListHandler : IRequestHandler<GetTraceableProductsListCommand, APIPaging<TraceableProductsDto>>
    {
        private readonly IBaseRepository<TraceableProductsModel> TraceableproductsRepository;
        private readonly ILogger<GetTraceableProductsListHandler> Logger;
        private readonly IMapper mapper;

        public GetTraceableProductsListHandler(IBaseRepository<TraceableProductsModel> traceableproductsRepository, ILogger<GetTraceableProductsListHandler> logger, IMapper mapper)
        {
            TraceableproductsRepository = traceableproductsRepository;
            Logger = logger;
            this.mapper = mapper;
        }
        /// <summary>
        /// 获取商品信息列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIPaging<TraceableProductsDto>> Handle(GetTraceableProductsListCommand request, CancellationToken cancellationToken)
        {
            APIPaging<TraceableProductsDto> res = new APIPaging<TraceableProductsDto>();
            var model = TraceableproductsRepository.GetALL().Where(x => x.IsDeleted == false);
            res.TotalCount = model.Count();
            var data = model.OrderByDescending(x => x.Id).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize);
            res.PageDatas = mapper.Map<List<TraceableProductsDto>>(data);
            res.Code = APIEnums.Success;
            res.Msg = "查询商品信息成功";
            Logger.LogInformation("查询商品信息成功");
            return Task.FromResult(res);
        }
    }
}
